package com.xxx.reportingsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.pojo.*;
import com.xxx.reportingsystem.service.RoleMenuService;
import com.xxx.reportingsystem.service.RoleService;
import com.xxx.service.UserOperateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@RequestMapping("/role")
@RestController
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserOperateService userOperateService;

    @Transactional
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('sys:add:role')")
    public Result addRole(@RequestBody Role role,@RequestParam(required = false,value = "menus") List<Integer> menus){
        if (Objects.isNull(role)){
            throw new RuntimeException("请求格式错误！");
        }
        if (menus != null && menus.size()>0){
            for (Integer menu : menus) {
                RoleMenu roleMenu = new RoleMenu(role.getRoleId(), menu, null, null);
                roleMenuService.save(roleMenu);
            }
        }
        LocalDateTime now = LocalDateTime.now();
        role.setCreateTime(now);
        role.setUpdateTime(now);
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        role.setCreateUser(loginUser.getUser().getName());
        role.setUpdateUser(loginUser.getUser().getName());
        boolean save = roleService.save(role);
        if (!save){
            throw new RuntimeException("添加角色失败！");
        }
        userOperateService.addLogManage("角色管理","添加角色","添加");
        return Result.success("添加角色成功!");
    }

    @Transactional
    @PostMapping("/select")
    public Result selectRoleByCondition(@RequestBody Role role, @RequestParam("current") Integer current, @RequestParam("size") Integer size){
        if (Objects.isNull(role)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(role.getRoleName() != null && role.getRoleName().length()>0,Role::getRoleName,role.getRoleName())
                .like(role.getRoleId() != null && role.getRoleId() >= 0,Role::getRoleId,role.getRoleId())
                .like(role.getRemark() != null && role.getRemark().length()>0,Role::getRemark,role.getRemark())
                .like(role.getStatus() != null,Role::getStatus,role.getStatus())
                .eq(Role::getStatus,0).eq(Role::getDelete,0);
        IPage iPage = new Page(current,size);
        IPage page = roleService.page(iPage,wrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("list",page.getRecords());
        map.put("total", page.getTotal());
        return Result.success("",map);
    }

    @Transactional
    @PutMapping("/update")
    public Result updateRoleById(@RequestBody Role role){
        if (Objects.isNull(role)){
            throw new RuntimeException("数据传输格式错误!~");
        }
        roleMenuService.update(new LambdaUpdateWrapper<RoleMenu>().set(RoleMenu::getStatus,1).eq(RoleMenu::getRoleId,role.getRoleId()));
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        role.setUpdateUser(loginUser.getUser().getName());
        role.setUpdateTime(LocalDateTime.now());
        boolean b = roleService.updateById(role);
        if (!b){
            throw new RuntimeException("修改角色失败！");
        }
        userOperateService.addLogManage("角色管理","修改角色","修改");
        return Result.success("修改角色成功!");
    }

    @Transactional
    @DeleteMapping("/delete")
    @PreAuthorize("hasAnyAuthority('sys:delete:role')")
    public Result deleteRoleByIds(@RequestParam("roleIds") List<Integer> roleIds){
        boolean b = false;
        if (!Objects.isNull(roleIds)){
            for (Integer roleId : roleIds) {
                b = roleService.removeById(roleId);
                roleMenuService.removeById(roleId);
            }
        }

        if (!b){
            throw new RuntimeException("删除角色失败！");
        }
        userOperateService.addLogManage("角色管理","删除角色","删除");
        return Result.success("删除角色成功!");
    }
}
